<?php

namespace app\admin\controller\bios;

use app\admin\model\Storea;
use app\common\controller\Backend;
use think\Db;
use think\exception\DbException;
use think\response\Json;

/**
 * 厂区生物库
 *
 * @icon fa fa-circle-o
 */
class Storage extends Backend
{

    /**
     * Storage模型对象
     * @var \app\admin\model\bios\Storage
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\bios\Storage;
        // 统计库存,
        $this->listModel = new \app\admin\model\Storem1 ;

        $this->view->assign("statusList", $this->model->getStatusList());

        $this->view->assign("storeaList", Storea::getList());
    }



    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->listModel
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);

        //  即时库存求和
        foreach($list->items() as  &$val){
            $sum_pro = Db::name("storepro")
                ->field("sum(cal_num) as all_num")
                //->where("storem1_id", $val['id'])
                ->where("storea_id", $val['storea_id'])
                ->where("factory_id", $val['factory_id'])
                ->find();
            $val['num'] = $sum_pro ? $sum_pro['all_num'] : 0 ;
        }

        foreach($list->items() as  &$val){
            $val['storea'] = $val['storea_id'] ;
            $val['factory'] = $val['factory_id'] ;
            //$val['storea_id'] = Db::name("storea")->where('id', $val['storea_id'])->find()['name'];
        }

        $list = $this->getXXX($list);

        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


}
